<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="chapter_id" label="章节" required>
        <uni-data-picker v-model="formData.chapter_id" collection="mydb-course-chapter" field="title as text, _id as value"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="word" label="单词" required>
         <uni-file-picker  return-type="object"  file-mediatype="all" :auto-upload="false" v-model="formData.word" @success="uploadSuccess" @select="selectFile">
			 <button type="primary" size="mini">选择Excel文件</button>
		 </uni-file-picker>
		<a href="https://mp-e3fbd118-dad0-4878-b40b-44597e7aa0eb.cdn.bspapp.com/单词模板.xlsx" download="单词模板.xlsx">下载模板</a>  
			<uni-table ref="table" :loading="loading" border stripe  emptyText="暂无更多数据" v-if="excelData.header">
				<uni-tr >
					<uni-th width="120" align="center" v-for="item in excelData.header">{{item}}</uni-th>
					<uni-th width="150" align="center" >操作</uni-th>
				</uni-tr>
				<uni-tr v-for="(item, index) in excelData.results" :key="index">
					<uni-td>{{ item['单词'] }}</uni-td>
					<uni-td>{{ item['中文释义'] }}</uni-td>
					<uni-td>{{ item['英文释义'] }}</uni-td>
					<uni-td>{{ item['例句'] }}</uni-td>
					<uni-td>
						<view class="uni-group">
							<button class="uni-button" size="mini" type="primary" @click="edit(item,index)">修改</button>
							<button class="uni-button" size="mini" type="warn" @click="remove(item,index)">删除</button>
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
	  </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
	<uni-popup ref="popup" border-radius="10px 10px 10px 10px" background-color="#fff">
		<uni-forms ref="form" style="width: 400px;">
		  <uni-forms-item :label="index" v-for="(item,index) in editData">
		    <uni-easyinput placeholder="请输入" v-model="editData[index]" trim="both" type="textarea" autoHeight></uni-easyinput>
		  </uni-forms-item>
		 
		  <view class="uni-button-group">
		    <button type="primary" class="uni-button" style="width: 100px;" @click="save">保存</button>
		  </view>
		</uni-forms>
	</uni-popup>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/mydb-course-unit.js';
  import XLSX from "xlsx";
  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'mydb-course-unit';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
		"chapter_id": "",
		"imgfile": null,
		"videofile": null,
		"audiofile": null,
		"word": "",
		"explain": "",
		"explainEn": "",
		"sort": null,
		"status": true,
		"example": ""
      }
      return {
        formData,
		excelData: {
		  header: null,
		  results: null,
		},
		loading:false,
		showPopup:false,
		editData:null,
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      /**
       * 验证表单并提交
       */
      submit() {
		  if(this.excelData.header && this.excelData.results && this.excelData.results.length){
			  uni.showLoading({
			    mask: true
			  })
			  this.$refs.form.validate().then((res) => {
			    return this.submitForm(res)
			  }).catch(() => {
			  }).finally(() => {
			    uni.hideLoading()
			  })
		  }else{
			  uni.showToast({
			  	title:'请选择导入文件',
				icon:'none'
			  })
		  }
      },

      /**
       * 提交表单
       */
      submitForm(value) {
		  
		  let concatData={
		  	"status": true,
		  	"chapter_id": this.formData.chapter_id,
			"sort": this.formData.sort,
			"imgfile": null,
			"videofile": null,
			"audiofile": null,
		  }
		  let options=[]
		  this.excelData.results.forEach((item)=>{
		  	options.push({
				...concatData,
				word: item['单词'],
				explain: item['中文释义'] || '__',
				explainEn: item['英文释义'] || '__',
				example: item['例句'] || '__',
		  	})
		  })
		  
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(options).then((res) => {
          uni.showToast({
            title: '导入成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },
	  uploadSuccess(e){
		  console.log(e)
	  },
	  selectFile(file){
		  console.log('file',file)
		  this.readerData(file.tempFiles[0]['file'])
	  },
	  generateData({ header, results }) {
	    this.excelData.header = header;
	    this.excelData.results = results;
		console.log(this.excelData)
	  },
	  readerData(rawFile) {
	    uni.showLoading()
		this.loading=true
	    return new Promise((resolve, reject) => {
	      const reader = new FileReader();
	      reader.onload = (e) => {
	        const data = e.target.result;
	        const workbook = XLSX.read(data, { type: "array" });
	        const firstSheetName = workbook.SheetNames[0];
	        const worksheet = workbook.Sheets[firstSheetName];
	        const header = this.getHeaderRow(worksheet);
	        const results = XLSX.utils.sheet_to_json(worksheet);
	        this.generateData({ header, results });
	        uni.hideLoading()
			this.loading=false
	        resolve();
	      };
	      reader.readAsArrayBuffer(rawFile);
	    });
	  },
	  getHeaderRow(sheet) {
	    const headers = [];
	    const range = XLSX.utils.decode_range(sheet["!ref"]);
	    let C;
	    const R = range.s.r;
	    /* start in the first row */
	    for (C = range.s.c; C <= range.e.c; ++C) {
	      /* walk every column in the range */
	      const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })];
	      /* find the cell in the first row */
	      let hdr = "UNKNOWN " + C; // <-- replace with your desired default
	      if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);
	      !hdr.includes('UNKNOWN') && headers.push(hdr);
	    }
	    return headers;
	  },
	  isExcel(file) {
	    return /\.(xlsx|xls|csv)$/.test(file.name);
	  },
	  edit(item,index){
		   this.$refs.popup.open('center')
		  this.editData=item
	  },
	  remove(item,index){
		  this.excelData.results.splice(index,1)
	  },
	  save(){
		   this.$refs.popup.close()
	  },
	  downTemplate(){
		  uni.saveFile({
			tempFilePath: 'https://mp-e3fbd118-dad0-4878-b40b-44597e7aa0eb.cdn.bspapp.com/单词模板.xlsx',
			success: function (res) {
			  var savedFilePath = res.savedFilePath;
			}
		  });
	  }
    }
  }
</script>
